package dao;

import pojo.Order;
import utils.JDBCUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class OrderDAO {

    private static final String TABLE_NAME = "tb_orders";

    // 全表查询，获取所有订单信息
    public static List<Order> getAllOrders() throws SQLException {
        List<Order> orders = new ArrayList<>();
        String sql = "SELECT * FROM " + TABLE_NAME;
        ResultSet resultSet = (ResultSet) JDBCUtils.execute(sql);
        while (resultSet.next()) {
            Order order = createOrderFromResultSet(resultSet);
            orders.add(order);
        }
        return orders;
    }

    // 新增订单（下单）
    public static void placeOrder(Order order) throws SQLException {
        order.setOrderDate(LocalDateTime.now());
        String sql = "INSERT INTO " + TABLE_NAME + " (user_id, book_id, book_name, quantity, order_date) VALUES (?, ?, ?, ?, ?)";
        JDBCUtils.execute(sql, order.getUserId(), order.getBookId(), order.getBookName(),
                order.getQuantity(), LocalDateTime.now());
    }

    // 创建 Order 对象从 ResultSet 中
    private static Order createOrderFromResultSet(ResultSet resultSet) throws SQLException {
        Order order = new Order();
        order.setOrderId(resultSet.getInt("order_id"));
        order.setUserId(resultSet.getString("user_id"));
        order.setBookId(resultSet.getInt("book_id"));
        order.setBookName(resultSet.getString("book_name"));
        order.setQuantity(resultSet.getInt("quantity"));
        order.setOrderDate(resultSet.getTimestamp("order_date").toLocalDateTime());
        return order;
    }
}
